package cn.cyk.test.servlet.app01a;

import javax.servlet.*;
import javax.servlet.Servlet;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * MyServlet
 *
 * @author YongKun CAO
 * @data 2018/11/3 12:54
 */
@WebServlet(name = "MyServlet", urlPatterns = {"/my"})
public class MyServlet implements Servlet {

    private transient ServletConfig servletConfig;

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        this.servletConfig = servletConfig;
    }

    @Override
    public ServletConfig getServletConfig() {
        return this.servletConfig;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse)
            throws ServletException, IOException {
        // 用servletConfig取出，servlet配置信息
        String servletName = servletConfig.getServletName();
        // 响应文本类型定义
        servletResponse.setContentType("text/html");
        // 响应内容编码格式定义，不定义默认PrintWriter会使用ISO-8859-1
        servletResponse.setCharacterEncoding("utf-8");
        // 响应内容写入,PrintWriter將文本传递给客户端
        PrintWriter writer = servletResponse.getWriter();
        writer.print("<html><head></head>"
                + "<body>Hello from " + servletName
                + "</body></html>");
    }

    @Override
    public String getServletInfo() {
        return "My Servlet";
    }

    @Override
    public void destroy() {

    }
}
